package cn.org.timespace.easyframe.util.sms;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.org.timespace.easyframe.util.sms.telecom.smsUtil.SMGPPropertie;

/**
 * jͨ����
 * */
public class UnicomMessage {
	private static final Log log =LogFactory.getLog(UnicomMessage.class);
	
	private static int sendType = Integer.parseInt(SMGPPropertie.getProperty("unicom.sendType","0").trim());// ���ŷ������� 0:httpclient   1:webService
	
	/*httpclient l�ӷ�ʽ ����*/
	//  http://ip:port/sms/Api/Send.do
	private static String ip = SMGPPropertie.getProperty("unicom.ip").trim();//l�ӵ�ַ
	private static String unicomUrl = SMGPPropertie.getProperty("unicom.url").trim();//httpclientl�ӵ�ַ
	private static String port = SMGPPropertie.getProperty("unicom.port").trim();//l�Ӷ˿�
	private static String spCode =SMGPPropertie.getProperty("unicom.spCode").trim();//��ҵ���
	private static String loginName = SMGPPropertie.getProperty("unicom.loginName").trim();//�û����
	private static String password = SMGPPropertie.getProperty("unicom.password").trim();//�û�����
	//private static String MessageContent = "";//��������, ���700���ַ�
	//private static String UserNumber = "";//Ŀ�ĺ���(�������á�,���ָ�)�����1000�����
	private static String serialNumber=SMGPPropertie.getProperty("unicom.serialNumber").trim();//��ˮ�ţ�20λ���֣�Ψһ 
	//private static String ScheduleTime = "";//��ʽ:yyyyMMddhhmmss,�确20090901010101��
	private static String ftype = SMGPPropertie.getProperty("unicom.ftype").trim();//�ύʱ��ⷽʽ  1 ���ύ��������Ч�ĺ����������ţ���Ч�ĺ����ڷ��ز���faillist���г�Ϊ1 ��ò������ --- �ύ������ֻҪ����Ч�ĺ��룬��ô���еĺ��붼��������ţ����еĺ����ڷ��ز���faillist���г�
	
	/*webService l�ӷ��� ����  SmsRequest*/
	private static String webserviceUrl = SMGPPropertie.getProperty("unicom.webserviceUrl");//webServicel�ӵ�ַ
	private static String sendMethods = SMGPPropertie.getProperty("unicom.sendMethods");//�ӿڷ��ͷ���
	
	
	
	
	
	public UnicomMessage(){
		if(sendType==0){
			//ʹ�õ��� httpclient ��ʽ���Ͷ��� ��Ҫ��b httpl��
			sendPost();
		}
	}
	
	//ÿ��post����֮��ķָ�    
    private static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";  
	// ����post� strParams 1:key 2:value    
    private static List<String[]> strParams;    
    // �ļ���post� fileParams 1:fileField, 2.fileName, 3.fileType, 4.filePath    
//    private static List<String[]> fileParams;
    
    /** 
     * Javaģ��Post�ύ 
     * @param url Ҫ�ύ����λ�� 
     * @param data ���磺NameValuePair[] data = {new NameValuePair("key", "nike"),new NameValuePair("proClass", "")}; 
     * @return ����HTML���� 
     */  
    public static synchronized String methodPost(String url,NameValuePair[] data){  
          
        String response= "";//Ҫ���ص�response��Ϣ  
        HttpClient httpClient = new HttpClient();  
        PostMethod postMethod = new PostMethod(url);  
        // ���?��ֵ����postMethod��  
        postMethod.setRequestBody(data);  
        // ִ��postMethod  
        int statusCode = 0;  
        try {  
        	HttpMethodParams params = new HttpMethodParams();
        	params.setContentCharset("GB2312");
        	postMethod.setParams(params);
            statusCode = httpClient.executeMethod(postMethod);  
        } catch (HttpException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        // HttpClient����Ҫ����ܺ�̷����������POST��PUT�Ȳ����Զ�����ת��  
        // 301����302  
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY  
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
            // ��ͷ��ȡ��ת��ĵ�ַ  
            Header locationHeader = postMethod.getResponseHeader("location");  
            String location = null;  
            if (locationHeader != null) {  
                location = locationHeader.getValue();  
                log.info("The page was redirected to:" + location);  
                response= methodPost(location,data);//����ת���ҳ����������  
            } else {  
                log.info("Location field value is null.");  
            }  
        } else {  
        	log.info(postMethod.getStatusLine());  
  
            try {  
                response= postMethod.getResponseBodyAsString();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            postMethod.releaseConnection();  
        }  
        return response;  
    } 
    
	/*
	 * Javaģ��Post�ύ 
	 * �˷�����ʱû�е�ͨ 
	 * */
	private static synchronized byte[] sendPost(){
		//httpl����    
        HttpURLConnection hc = null;    
        //byte�������4��ȡ������ص���Ϣ    
        ByteArrayOutputStream bos = null;    
        //��������4��ȡ������ص���Ϣ    
        InputStream is = null;    
        //���������ص���Ϣ��byte����    
        byte[] res = null;    
        
        try {    
            URL url = new URL(unicomUrl);    
            hc = (HttpURLConnection) url.openConnection();    
    
            hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);    
            hc.setRequestProperty("Charsert", "GB2312");    
            // ����POST���������������}��    
            hc.setDoOutput(true);    
            hc.setDoInput(true);    
            hc.setUseCaches(false);    
            hc.setRequestMethod("POST");    
    
            OutputStream dout = hc.getOutputStream();    
            ////1.��д������ʽ��post��    
            //ͷ    
            String boundary = BOUNDARY;    
            //��    
            StringBuffer resSB = new StringBuffer();    
            //β    
            //strParams 1:key 2:value    
            if(strParams != null){    
                for(String[] parsm : strParams){    
                    String key = parsm[0];    
                    String value = parsm[1];  
                    resSB.append(key).append("=").append(value).append("&");
                }    
            }    
            String boundaryMessage = resSB.substring(0,(resSB.length() - 1)).toString();    
                
            //д����    
            dout.write((boundaryMessage).getBytes("GB2312") );
                
            dout.close();    
                
            int ch;    
    
            is = hc.getInputStream();    
            //�յ��Ļ�ִ    
            bos = new ByteArrayOutputStream();    
            while ((ch = is.read()) != -1) {    
                bos.write(ch);    
            }    
            res = bos.toByteArray();    
        } catch (Exception e) {    
            e.printStackTrace();    
        } finally {    
            try {    
                if (bos != null)    
                    bos.close();    
    
                if (is != null)    
                    is.close();    
    
            } catch (Exception e2) {    
                e2.printStackTrace();    
            }    
        }    
        
        return res;    
    } 
	
	/**
	 * ������Ϣ
	 * @param String mobiles notnull Ŀ�ĺ���(�������á�,���ָ�)�����1000�����
	 * @param String content notnull ��������, ���700���ַ�
	 * */
	public static String send(String mobiles,String content){
		String result = "";
		if(sendType==0)
			result = httpClientSend(mobiles,content);
		else
			result = webServiceSend(mobiles,content);
		return result;
		
	}
	/**
	 * httpclient
	 * */
	private static String httpClientSend(String mobiles,String content){
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		/*strParams = new ArrayList<String[]>();
		strParams.add(new String[]{"SpCode",spCode});
		strParams.add(new String[]{"LoginName",loginName});
		strParams.add(new String[]{"Password",password});
		strParams.add(new String[]{"MessageContent",content});
		strParams.add(new String[]{"UserNumber",mobiles});
		strParams.add(new String[]{"SerialNumber",serialNumber});
		strParams.add(new String[]{"ScheduleTime",format.format(new Date())});
		strParams.add(new String[]{"f",ftype});
		byte[] res = sendPost();
		String result = "";
		try {
			result = new String(res,"GB2312");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log.info("httpClientSend result:"+result);
		*/
		
		NameValuePair[] pair = {new NameValuePair("SpCode",spCode),
				new NameValuePair("LoginName",loginName),
				new NameValuePair("Password",password),
				new NameValuePair("MessageContent",content),
				new NameValuePair("UserNumber",mobiles),
				new NameValuePair("SerialNumber",serialNumber),
				new NameValuePair("ScheduleTime",format.format(new Date())),
				new NameValuePair("f",ftype)};
		
		String res = methodPost(unicomUrl,pair);
		
		log.info("jͨhttp�ӿڷ��Ͷ��ŷ���ֵ��"+res);
		
		String result="";
		if(res!=null&&res.length()>0){
			String[] ress = res.split("&");
			if(ress.length>0){
				String[] resu = ress[0].split("=");
				if(resu.length>0)
					result = resu[1];
			}
		}
		log.info("jͨhttp�ӿڷ��Ͷ���״̬��"+result);
		return result;
	}
	
	
	/**
	 * webservice
	 * */
	private static String webServiceSend(String mobiles,String content){
		log.info("jͨwebService�ӿڷ��Ͷ��ŷ���ֵ��");
		return null;
	}
	/**
	 * ������Ϣ
	 * */
	public void receive(){
		
		
	}
}
